package com.abhimanyu.bootstrap.facade;

import java.util.ArrayList;
import java.util.List;

import com.abhimanyu.dataaccess.IDao;
import com.abhimanyu.dataaccess.model.User;
import com.abhimanyu.messaging.IMessageSender;
import com.abhimanyu.messaging.model.IMessage;
import com.abhimanyu.messaging.model.TextMessage;
import com.abhimanyu.service.ICurrencyRateObserver;
import com.abhimanyu.service.model.DollarRateServiceData;

public class DollarRateNotifierServiceImpl implements
		IDollarRateNotifierService {

	private List<ICurrencyRateObserver> currencyRateObserverList;
	private IDao<User> userDao;
	private IMessageSender messageSender;

	public void sendDollarRateChangeNotification() {
		List<User> listOfRegisteredUsers = userDao.fetchAll();
		List<String> rates = getDollarRatesFromServices();
		String messageText = constructMessageText(rates);
	
		List<IMessage> listOfMessages = transformToMessage(
				listOfRegisteredUsers, messageText);
		
		/*List<IMessage> listOfMessages = new ArrayList<IMessage>();
		TextMessage message = new TextMessage();
		message.setMessageText("trial 1");
		message.setPhoneNumber("+17858069227");
		listOfMessages.add(message);*/
		sendMessages(listOfMessages);
	}

	private List<String> getDollarRatesFromServices() {
		List<String> dollarRates = new ArrayList<String>();
		for (ICurrencyRateObserver service : currencyRateObserverList) {
			for (DollarRateServiceData dollarRateData : service.getCurrentDollarRate()) {
				dollarRates.add(service + " : "	+ dollarRateData.getDollarRateData());
			}			
		}		
		return dollarRates;
	}

	private String constructMessageText(List<String> rates) {
		StringBuffer sb = new StringBuffer();
		String messageText = null;
		sb.append("Dollar rate today is");
		for (String rate : rates) {
			sb.append("\n- ").append(rate);
		}

		sb.append("\n- Service by Abhimanyu's Daily Dollar Rate Notifier.");
		messageText = sb.toString();
		return messageText;
	}

	private List<IMessage> transformToMessage(List<User> list,
			String messageText) {
		List<IMessage> messagesList = new ArrayList<IMessage>();
		TextMessage message = null;
		for (User user : list) {
			message = new TextMessage();
			message.setScheduledAt(user.getScheduledAt());
			message.setPhoneNumber(user.getMobileNumber());
			message.setMessageText(messageText);
			messagesList.add(message);
		}

		return messagesList;
	}

	private void sendMessages(List<IMessage> messagesList) {
		for (IMessage message : messagesList) {
			messageSender.sendMessage(message);
		}
	}

	public void setCurrencyRateObserverList(
			List<ICurrencyRateObserver> currencyRateObserverList) {
		this.currencyRateObserverList = currencyRateObserverList;
	}

	public void setUserDao(IDao<User> userDao) {
		this.userDao = userDao;
	}

	public void setMessageSender(IMessageSender messageSender) {
		this.messageSender = messageSender;
	}
}
